// Copyright (c) 2010 god6or@gmail.com under MIT license.

import java.io.{File, FileOutputStream, FileInputStream}
import java.util.{Locale}
import java.awt.{Dimension, Rectangle}
import javax.swing.{Box, BoxLayout}
import swing.{Action, Orientation, SimpleSwingApplication, MainFrame, BoxPanel, BorderPanel, ComboBox, TabbedPane, Label, Button, Swing, FileChooser}
import collection.mutable.{ Buffer, ArrayBuffer }

import ul.iobj.{IAttr, IObj}
import ul.gettext.{GetText}

import ul.ownet.{Config, DB, Sensors, CfgPanel, ViewPanel}

object OWNet extends SimpleSwingApplication {

    def top = new MainFrame {

        // load configuration
        try {
            val cfgIn = new FileInputStream(Config.confFile)
            Config.attrsFromConf( new String((for (i <- 1 to cfgIn.available()) yield cfgIn.read().toByte).toArray, "utf8") )
            cfgIn.close()
        } catch { case _ => }

        // load localization
        Config.tran = new GetText("./locale", Config.projectName)
        Config.tran.lang = Config("lang").s
        val tr: (String)=>String = Config.tran.tr _
        val loc = new Locale( Config.tran.lang )
        Locale.setDefault(loc)
        
        // build GUI
        title = tr("OWNet")


        val csvOpenButton = new Button { action = new Action( tr("open") ) {
            toolTip = tr("open saved data")
            xLayoutAlignment = 0.0F
            val csvLoadDialog = new FileChooser {
                title = tr("Load from CSV file")
                fileSelectionMode = FileChooser.SelectionMode.FilesOnly
                multiSelectionEnabled = false
            }
            override def apply() = {
                csvLoadDialog.selectedFile = new File( Config("pollLastLocation").s + File.separator + "*.csv" )
                if (csvLoadDialog.showOpenDialog( downPanel.tabs ) == FileChooser.Result.Approve) {
                    if (csvLoadDialog.selectedFile.exists) {
                        Config("pollLastLocation").s = csvLoadDialog.selectedFile.getParentFile.getCanonicalPath
                        
                        val newTab = new ViewPanel( downPanel.tabs, false )
                        newTab.title = csvLoadDialog.selectedFile.getName
                        newTab.tip = csvLoadDialog.selectedFile.getCanonicalPath
                        newTab.db.clear
                        newTab.db.fromCSV( csvLoadDialog.selectedFile.getCanonicalPath )
                        newTab.chartUpdate()
                        downPanel.tabs.pages += newTab
                        downPanel.tabs.selection.index = downPanel.tabs.pages.length - 1
                        tabCloseButton.enabled = true
                    }
                }
            }
        }}
        
        val tabCloseButton: Button = new Button { val thisButton = this; action = new Action( tr("close") ) {
            toolTip = tr("close tab")
            xLayoutAlignment = 0.0F
            enabled = false
            override def apply() = {
                if (downPanel.tabs.selection.index >= 2) {
                    downPanel.tabs.pages -= downPanel.tabs.pages( downPanel.tabs.selection.index )
                    if (downPanel.tabs.pages.length == 2) thisButton.enabled = false
                }
            }
        }}

        val upPanel = new BoxPanel(Orientation.Horizontal) { // upper panel

            contents ++= List(
                new BoxPanel(Orientation.Horizontal) {
                    xLayoutAlignment = 0.0F
                    yLayoutAlignment = 0.0F
                    peer.setBorder( new javax.swing.border.EtchedBorder )
                    contents ++= List(
                        csvOpenButton
                        ,tabCloseButton
                        ,Swing.HGlue
                    )
                }
                //,Swing.HGlue
            )
        }
        val downPanel = new BoxPanel(Orientation.Horizontal) { // lower panel
            val tabs = new TabbedPane()

            // configuration page
            val cfgPanel = new CfgPanel( tabs )
            tabs.pages += cfgPanel

            // chart view/poll page
            val pollPanel = new ViewPanel( tabs, true )
            tabs.pages += pollPanel
            
            // restore all pages opened in last session
            for (dbFile <- Config("openedFiles").s.split(";")) {
                if (new File(dbFile).exists)
                    tabs.pages += new ViewPanel( tabs, false, dbFile )
            }
            
            if (Config("tabIndex").i < tabs.pages.length) tabs.selection.index = Config("tabIndex").i
            else tabs.selection.index = tabs.pages.length - 1;

            if (tabs.pages.length > 2) tabCloseButton.enabled = true
            
            contents += tabs
        }
        val mainPanel = new BorderPanel {
            add( upPanel, BorderPanel.Position.North )
            add( downPanel, BorderPanel.Position.Center )
        }
        contents = mainPanel

        minimumSize = new Dimension( 750, 550 )
        bounds = new Rectangle( Config("winX").i, Config("winY").i, Config("winW").i, Config("winH").i )
        
        downPanel.pollPanel.db.open
        downPanel.pollPanel.db.fromCSV( Config.dbFile )
        downPanel.pollPanel.chartUpdate(true)

        
        override def closeOperation() {
            
            // update configuration
            Config("winX").i = bounds.x; Config("winY").i = bounds.y;
            Config("winW").i = bounds.width; Config("winH").i = bounds.height;
            Config("tabIndex").i = downPanel.tabs.selection.index;
            var of = ""
            for (ti <- 2 to downPanel.tabs.pages.length-1)
                of += downPanel.tabs.pages(ti).tip + ";";
            Config("openedFiles").s = of
            downPanel.cfgPanel.toCfg

            // save configuration
            val cfgOut = new FileOutputStream(Config.confFile)
            cfgOut.write( Config.attrsToConf.getBytes( "utf8" ) )
            cfgOut.close
            
            // save current DB
            downPanel.pollPanel.db.toCSV( Config.dbFile )
            downPanel.pollPanel.db.close

            super.closeOperation()
        }
    }

}

